#!/usr/bin/env python
#coding=utf-8
import Timer
import urllib.request
import json
import time
import Logger_Class
import docheck
token=''
corpid = 'ww03c5a1fa843d0a4a'
corpsecret = 'W4s6NZl6iNLV38cXifW-RTkzUE7rR9njrzJrqTTTjeg'
url = 'https://qyapi.weixin.qq.com'

logger = Logger_Class.Logger_test(logname='D:/log4.txt', loglevel='1', logger="Util").getlog()

#--------------------------------
# 更新token
#--------------------------------
def  updateToken():
       logger.info('执行更新token操作')

       token_url = '%s/cgi-bin/gettoken?corpid=%s&corpsecret=%s' % (url, corpid, corpsecret)
       print(token_url)
       print(urllib.request.urlopen(token_url).read().decode())
       logger.info(urllib.request.urlopen(token_url).read().decode())
       logger.info('更新开始')
       global  token
       token = json.loads(urllib.request.urlopen(token_url).read().decode())['access_token']
       logger.info('更新结束')
       #global token
       #token =token+'3'
       print(token)


#--------------------------------
# 返回最新的token
#--------------------------------
def getToken():
       print('获取token')
       logger.info('获取token='+token)
       return token


#--------------------------------
# 构建告警信息json
#--------------------------------
def messages(msg):
    values = {
        "touser": '@all',
        "msgtype": 'text',
        "agentid": 1000003, #偷懒没有使用变量了，注意修改为对应应用的agentid
        "text": {'content': msg},
        "safe": 0
        }
    msges=(bytes(json.dumps(values), 'utf-8'))
    return msges

#--------------------------------
# 发送告警信息
#--------------------------------
def send_message():
        #msg = '信息科技部,Python调用企业微信测试，当前时间为：' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        msg='blackeye于'+time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))+'进行网络巡检，巡检结果如下：\n'
        msg+=docheck.doCheck()
        data = messages(msg)
        send_url = '%s/cgi-bin/message/send?access_token=%s' % (url,token)
        respone=urllib.request.urlopen(urllib.request.Request(url=send_url, data=data)).read()
        x = json.loads(respone.decode())['errcode']
        # print(x)
        if x == 0:
            print ('Succesfully')
        else:
            print ('Failed')
            updateToken()








#Timer.setTime(test, 2, [werwre])



